/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.cef.generator.repository.dac.property;


import com.inspur.edp.caf.generator.baseInfo.TypeInfo;
import com.inspur.edp.caf.generator.property.ClassPropertyGenerator;
import com.inspur.edp.cef.entity.dependenceTemp.DataValidator;
import com.inspur.edp.cef.generator.repository.AssemblerInfo;
import com.inspur.edp.cef.generator.repository.RepositoryGenUtil;
import com.inspur.edp.cef.generator.repository.dac.DataTypeDacGenContext;
import com.inspur.edp.cef.repository.assembler.DataTypeAssembler;
import com.inspur.edp.cef.repository.assembler.entity.ColumnInfo;
import com.inspur.edp.cef.repository.assembler.entity.DbTableInfo;
import com.inspur.edp.cef.repository.assembler.entity.MainEntityAssembler;
import com.inspur.edp.cef.repository.sqlgenerator.BaseSqlGenerator;
import com.inspur.edp.lcm.databaseobject.api.DatabaseObjectServiceForWebIde;
import io.iec.edp.caf.databaseobject.api.entity.DatabaseObjectTable;
import io.iec.edp.caf.databaseobject.api.entity.DatabaseObjectTableCore;
import io.iec.edp.caf.databaseobject.api.service.IDatabaseObjectRtService;
//import io.iec.edp.caf.databaseobject.api.service.IDatabaseObjectService;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.StringLiteral;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;

public class ParentJoinPropGneratpr extends ClassPropertyGenerator {
	private BaseSqlGenerator sqlGenerator;
	private String parentIdColumnName;
	private final DataTypeDacGenContext dacContext;
	private MainEntityAssembler parentAssembler;
	private DbTableInfo parenTableInfo;
	private DatabaseObjectTableCore dbo;
	private final AssemblerInfo baseAssemblerInfo;
	private boolean isChild;

	public ParentJoinPropGneratpr(BaseSqlGenerator sqlGenerator, String parentIdColumnName, AssemblerInfo baseAssemblerInfo, boolean isChild, DataTypeDacGenContext dacContext) {
		this.baseAssemblerInfo = baseAssemblerInfo;
		this.isChild = isChild;
		this.sqlGenerator = sqlGenerator;
		this.parentIdColumnName = parentIdColumnName;
		this.dacContext = dacContext;
		DataTypeAssembler tempVar = baseAssemblerInfo.getAssemblerInstance();
		parentAssembler = ((MainEntityAssembler) ((tempVar instanceof MainEntityAssembler) ? tempVar : null)).getParentAssembler();

		if (parentAssembler != null) {
			initTableInfo();
		}
	}
//
//	@Autowired
//	private IDatabaseObjectRtService dboservice;


	///#region Init
	private void initTableInfo() {
		parenTableInfo = parentAssembler.getTableInfo();
		String dboId = parentAssembler.getTableInfo().getDboId();

//		var rtService = ServiceManager.<IDatabaseObjectRtService>getService();
		String path =dacContext.getReposContext().getCefContext().getCefGenContext().getMetadataPath();
		//IDatabaseObjectService dboservice = RepositoryGenUtil.getBeanByType(IDatabaseObjectService.class);
		DatabaseObjectServiceForWebIde dboservice = RepositoryGenUtil.getBeanByType(DatabaseObjectServiceForWebIde.class);
//		IDatabaseObjectRtService dboservice = RepositoryGenUtil.getBeanByType(IDatabaseObjectRtService.class);
		Object tempVar = dboservice.getDatabaseObjectById(path, dboId);
		dbo = (DatabaseObjectTableCore) ((tempVar instanceof DatabaseObjectTableCore) ? tempVar : null);
		DataValidator.checkForNullReference(dbo, "dbo");
		parenTableInfo.setTableName(dbo.getCode());
		//已经不需要了
		//parenTableInfo.setIsFiscal(dbo.isFiscalTable());
	}

	@Override
	protected TypeInfo getPropertyType() {
		return new TypeInfo(String.class);
	}

	@Override
	protected String getFieldName() {
		return null;
	}

	@Override
	protected String getPropertyName() {
		return "ParentJoin";
	}

	@Override
	protected boolean isGetterOverride() {
		return true;
	}

	@Override
	protected boolean isSetterOverride() {
		return true;
	}

	@Override
	protected ArrayList<Modifier.ModifierKeyword> getGetterAccessModifier() {
		ArrayList<Modifier.ModifierKeyword> list = new ArrayList<>();
		list.add(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
		return list;
	}

	@Override
	protected ArrayList<Modifier.ModifierKeyword> getSetterAccessModifier() {
		return null;
	}


	@Override
	protected boolean hasSetMethod() {
		return false;
	}

	@Override
	protected Block buildGetMethodBody() {
		Block block = ast.newBlock();
		if (!isChild) {
			ReturnStatement returnStatement = ast.newReturnStatement();
			returnStatement.setExpression(ast.newNullLiteral());
			block.statements().add(returnStatement);
		} else {
			String joinTable = getJoinTable();
			StringLiteral stringLiteral = ast.newStringLiteral();
			stringLiteral.setLiteralValue(joinTable);
			ReturnStatement returnStatement = ast.newReturnStatement();
			returnStatement.setExpression(stringLiteral);
			block.statements().add(returnStatement);
		}

		return block;
	}


	///#endregion
	private String getJoinTable() {
		String parenTableName = "@ParentTableName@  " + parenTableInfo.getAlias(); // getParentTableName();//{3}
		String parentPrimaryKey = getParentTablePrimaryKey(); //{5}
		if (parentPrimaryKey .equals("" )|| parentPrimaryKey == null) {
			throw new RuntimeException("未找到父表主键字段，请检查配置");
		}
		return String.format(sqlGenerator.getInnerJoinTableName(), parenTableName, parentIdColumnName, parentPrimaryKey);
	}

	private String getParentTablePrimaryKey() {
		String alias = parenTableInfo.getAlias();

		for (ColumnInfo column : parentAssembler.getContainColumns()) {
			if (column.getIsPrimaryKey()) {

				String dbColumnName = dbo.getColumnById(column.getDboColumnId()).getCode();
				return alias + "." + dbColumnName;
			}
		}
		return null;
	}
}
